package com.cloudbroker.bcs.platform.ltb.middle.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.cloudbroker.bcs.common.util.ExceptionMsgUtil;
import com.cloudbroker.bcs.csvc.credits.api.vo.back.IntegralBackVO;
import com.cloudbroker.bcs.platform.ltb.bizapi.constants.HSBCPSErrorCodes;
import com.thinkive.openservice.api.TKOpenServiceClient;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by daibd19671 on 2017/02/06.
 */
public class MiddleTKOpenServiceUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(MiddleTKOpenServiceUtil.class);

    public static final String  INTEGRAL_CONSUM="200021";
    public static final String  INTEGRAL_ADD="200022";
    public static final String  INTEGRAL_QUERY="200023";
    public static final String  TEMPLATE_PUSH="1002900";


    public static <T> T requestMethod(String functionId,
                                   Map<String, String> params,Class<T> clazz) {
        params.put("source", "1");
        String result ="";
        Map<String,Object> resultMap = new HashMap<>();
        try{
            result = TKOpenServiceClient.sendData(functionId, params);
            resultMap = JSON.parseObject(result,Map.class);
        }catch (Exception e){
            LOGGER.error("functionId :"+functionId +"-----请求异常："+e);
            String errorMsg= ExceptionMsgUtil.getExceptionMsg(e);
            resultMap.put("error_no",HSBCPSErrorCodes.TKOpenErrorInfo.REQUEST_ERR);
            resultMap.put("error_info",errorMsg);
            T resultClass = JSON.parseObject(JSON.toJSONString(resultMap),clazz);
            return resultClass;
        }
        if(StringUtils.isBlank(result)){
            LOGGER.error("functionId :"+functionId +"-----请求结果为空");
            return null;
        }
        Map<String,Object> returnMap=new HashMap<>();
        if("0".equals(resultMap.get("error_no"))){
            JSONArray jsonArray = (JSONArray) resultMap.get("results");
            String resultString = JSON.toJSONString( jsonArray.get(0));
            returnMap =  JSON.parseObject(resultString,Map.class);
        }
        returnMap.put("error_no",resultMap.get("error_no"));
        returnMap.put("error_info",resultMap.get("error_info"));
        LOGGER.error("functionId :"+functionId +"-----请求结果为："+result);
        T resultClass = JSON.parseObject(JSON.toJSONString(returnMap),clazz);
        return resultClass;
    }

}
